package com.example.blog.controller;

import com.example.blog.pojo.Blog;
import com.example.blog.pojo.Comment;
import com.example.blog.pojo.User;
import com.example.blog.pojo.query.SearchBlog;
import com.example.blog.service.BlogService;
import com.example.blog.service.CommentService;
import com.example.blog.utils.MarkdownUtils;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * name: 东北宋小宝
 * date: 2020/9/1
 */
@Controller
public class BlogShowController {
    @Resource
    private BlogService blogService;
    @Resource
    private CommentService commentService;
    @Value("${blogpage.userAvatar}")
    private String userAvatar;
    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Integer id, Model model){
        Blog blog = blogService.getBlog(id);
        blog.setContent(MarkdownUtils.markdownToHtmlExtensions(blog.getContent()));
        model.addAttribute("blog",blog);
        return "blog";
    }
    @PostMapping("/comments")
    public String post(Comment comment, Model model) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if (user != null) {
            comment.setAvatar(user.getAvatar());
            comment.setNickname(user.getNickname());
        } else {
            comment.setAvatar(userAvatar);
        }
        comment.setCreatTime(new Date());
        int id = comment.getBlogId().intValue();
        commentService.saveComment(comment);
        model.addAttribute("blog",blogService.getBlog(id));
        return "blog :: comment";
    }
    @PostMapping("/blog/search")
    public String search(SearchBlog searchBlog, Model model){
        PageInfo pageInfo = blogService.queryPage(1, 7, searchBlog);
        model.addAttribute("pageInfo", pageInfo);
        return "search";
    }

    @GetMapping("/comments/{blogid}/del/{id}")
    public String del(@PathVariable String blogid,@PathVariable Long id){
        commentService.delComment(id);
        return "redirect:/blog/"+blogid;
    }
    @GetMapping("/archives")
    public String toArchives(Model model){
        List allBlog = blogService.getAllBlog();
        model.addAttribute("blogs",allBlog);
        return "archives";
    }
}
